from sched import scheduler
from flask.blueprints import Blueprint
from flask import Flask
from config import config
from redis import StrictRedis
from flask_cors import CORS
from flask_caching import Cache
from concurrent.futures import ThreadPoolExecutor
from flask_sqlalchemy import SQLAlchemy
from flask_apscheduler import APScheduler

# redis缓存
redis_client: StrictRedis = None


# 配置跨域
cors = CORS()

# 线程池
executor = None

# 请求缓存
cache = None

# 数据库
db = SQLAlchemy()

# 定时任务
scheduler = APScheduler()


def create_app(config_name: str) -> Flask:
    # 读取配置信息
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)


    # 配置响应缓存
    global cache
    cache = Cache(config={
        'CACHE_TYPE': 'RedisCache',
        'CACHE_REDIS_HOST': app.config['REDIS_HOST'],
        'CACHE_REDIS_PORT': app.config['REDIS_PORT'],
        'CACHE_REDIS_PASSWORD': 'fisherkk',
        'CACHE_KEY_PREFIX': 'paper:rec_sys:'
    })
    cache.init_app(app)

    #  进行一些初始化操作
    # 0. 配置跨域
    cors.init_app(app, resources={
        '/api/*': {'origins': '*'}
    })

    # 1. 初始化Redis
    global redis_client
    redis_client = StrictRedis(host=app.config['REDIS_HOST'],
                               port=app.config['REDIS_PORT'])

    # 2. 初始化DB
    db.init_app(app)
    
    # 3. 配置线程池
    global executor
    executor = ThreadPoolExecutor(10)

    # 4. 定时任务
    scheduler.init_app(app)
    scheduler.start()
    

    # 导入不同的蓝图
    from .api import api as api_blueprint
    app.register_blueprint(api_blueprint, url_prefix='/api')  # 导入接口

    # 工厂生产app
    return app
